//  初始化请求配置
const settingApp=(vm)=>{
	 //初始化模板变量
	vm.config.globalProperties.$tempDataInit = function(temp,obj,item){
		for (let key in temp) {
			let value_type = typeof temp[key]
			let value = item[key];
			let default_value = undefined
			if( temp[key] instanceof Array ) {
				default_value = []
			}else if(temp[key] instanceof Object){
				default_value = {}
			}else if(value_type === 'string' ) {
				default_value = ""
				value = (value||'') + ""
			}else if(value===0){
				default_value = 0
			}
			obj[key] = value||default_value
		}
	}
	 //添加网络请求插件
	const $network = function(api,params={},options={},method="post"){
		return new Promise((resolve,reject)=>{
			uni.$u.http[method](api, params, !(options instanceof Function) ? options : {
				custom:{
					completeFnc:(res)=>{
						options(res)
					}
				}
			}).then(res => {
				resolve(res)
			}).catch(err=>{
				reject(err)
			})
		})
	}
	uni.$network = $network
	vm.config.globalProperties.$network =$network
	
	
	//页面跳转
	vm.config.globalProperties.$multiRedirect=function(url,loginState){
		console.log('>>>>>>>>>>>>$multiRedirect',url)
		if ( loginState === true ) {
			if(!this.vuex_user_id){
				uni.$emit('loginEvent')
				return
			}
		}
	    if(url===-1){
			uni.navigateBack()
		}else if(url && url.length>0){
			console.log('+++++',url.indexOf('http'))
	        if(url.indexOf('http')===0){
				// #ifdef H5 
					location.href=url
				// #endif
				// #ifdef MP-WEIXIN
					 uni.navigateTo({ 
						 url:'/pages/web/web?url='+encodeURIComponent(url)
					 })
				// #endif
				// #ifdef APP-PLUS
				plus.runtime.openURL(url, function(res) {  
					console.log(res);  
				});
				// #endif
			}else if(url.indexOf('&switch')>-1){
	            uni.switchTab({url})
	        }else {
	            uni.navigateTo({ url})
	        }
	    }
	}
	//拨打电话
	vm.config.globalProperties.$makePhoneCall=function(tel){
		console.log("makePhoneCall",tel)
		// uni.showModal({
		// 	content: '立即拨打电话?',
		// 	success: function (res) {
		// 		if (res.confirm) {
					uni.makePhoneCall({
						phoneNumber:tel+'',
						success() {
							console.log('success')
						},
						fail() {
							console.log('fail')
						}
					})
		// 		} else if (res.cancel) {
		// 			console.log('用户点击取消');
		// 		}
		// 	}
		// });
		
	}
	
	//
	vm.config.globalProperties.$setClipboard=function (content) {
	
		uni.setClipboardData({
			data: content,
			success: function() {
				uni.$u.toast('复制成功')
			}
		});
	},
	
	//showModal
	vm.config.globalProperties.$showModal = function(json){
		return uni.showModal(Object.assign({
			success: (res) => {
				
				
			}
		},json))
	}
	
	//json
	vm.config.globalProperties.$jsonToQuery = function(json){
		let query = ''
		Object.keys(json).map(function(key){
			query += key + '='+json[key]+'&'
		})
		console.log(query)
		return query.length > 0 ? query.substring(0,query.length-1): query;
	}
	//json
	vm.config.globalProperties.$previewImage = function(img){
		let showImages = [img]
		if(img instanceof Array){
			showImages = img;
		}
		uni.previewImage({
			urls: showImages,
		});
	}
	
	vm.config.globalProperties.$weixin_qrcodeQueryString = function (url, name) {
	  var reg = new RegExp('(^|&|/?)' + name + '=([^&|/?]*)(&|/?|$)', 'i')
	  var r = url.substr(1).match(reg)
	  if (r != null) {
		return r[2]
	  }
	  return null;
	}
	
	
	/*
	获取缓存数据-有就读取,没有 就网络请求
	obj-对象格式  {"数据类型":"缓存的键名"}
		获取商品分类 可使用 {goods_cate:goodsCateList}
	*/
	
	vm.config.globalProperties.$getCacheData = (function(){
		const cacheConfing = {}
		return function(obj,fnc,refresh){
			const forceRefresh = refresh===true
			if(!(fnc instanceof Function) || !(obj instanceof Object)){
				return 
			}
			let query = {}
			let results = {};
			if(forceRefresh){
				query = obj
			}else{
				Object.keys(obj).map(function(key){
					const valueKey = obj[key]
					if(!cacheConfing[valueKey]){
						query[key] = valueKey
					}else{
						//绑定缓存数据
						results[valueKey] = cacheConfing[valueKey]
					}
				})
				
			}
			
			if(!Object.keys(query).length){
				//返回数据
				fnc(results)
			}else{
				$network('/api/index/groupData',query).then((res)=>{
					const data = res.data||{}
					
					Object.keys(data).map(function(key){
						const value = data[key];
						results[key] = value;
						cacheConfing[key] = value;
					})
					//返回数据
					fnc(results)
				})
			}
			
			
			
		}
	})()
	
	//小程序二维码参数解析
	vm.config.globalProperties.$mpSceneDecode=(content) => {
		const scene = decodeURIComponent(content)
		var _str = scene + "";
		var _str_list = _str.split("&");
		var res = {};
		for (var i in _str_list) {
			var _tmp_str = _str_list[i];
			var _tmp_str_list = _tmp_str.split("=");
			if (_tmp_str_list.length > 0&&_tmp_str_list[0]) {
				res[_tmp_str_list[0]] = _tmp_str_list[1] || null;
			}
		}
		return res;
	}
	
	
	/**
	 * 通过图片url获取图片大小
	 *
	 * @param {String} imgsrc 例如图片名： D8x5f13a53dbc4b9_350x345.png
	 */
	vm.config.globalProperties.$getImageInfo=(imgsrc)=>{
	  let data = {
	    width: 0,
	    height: 0,
	  }
	
	  let arr = imgsrc.split('_')
	  if (arr.length == 1) return data
	
	  let info = arr[arr.length - 1].match(/\d+x\d+/g)
	  if (info == null) return data
	
	  info = info[0].split('x')
	  return {
	    width: parseInt(info[0]),
	    height: parseInt(info[1]),
	  }
	}
	
}
export {
	settingApp
}